const { img } = require("../../images/img.js");
// const {
//   btoa
// } = require('../../utils/base64.js')
import { drawRectangle1 } from "./utils.js";

const t = {};

Page({
  data: {
    /** 最小缩放百分比 */
    minScale: 70,
    /** 最大缩放百分比 */
    maxScale: 150,
    /** 单次缩放百分比增量 */
    increaseScale: 5,
    /** 缩放比例 */
    scale: 1,
    touchType: "",
    start: {
      x: 0,
      y: 0,
    },
    touches: [],
    change: {
      x: 0,
      y: 0,
    },
    /** 是否正在绘制 */
    drawing: false,
    // 视图宽度
    viewWidth: 0,
    // 视图高度
    viewHeight: 0,
    // 画布绘制的图像宽度
    width: 895,
    // 画布绘制的图像高度
    height: 690,
    uDData: {
      x: 150,
      y: 150,
    },
    numArr: [
      [10, 20, "1", 20, 20],
      [60, 20, "2", 20, 20],
      [90, 20, "3", 20, 20],
      [90, 60, "4", 20, 20],
    ],
    containerStyle: {
      width: 100,
      height: 70,
    },
  },

  checkwh(e) {
    var vhsrc = e.detail.height / e.detail.width;
    // let res = this.data.res
    // let byclear = this.data.byclear
    // const ctx = wx.createCanvasContext('canvasIn', this);
    // ctx.drawImage(res.tempFilePaths[0], 0, 0, e.detail.width, e.detail.height)
    // ctx.draw()
    // this.setData({
    //   imgW: e.detail.width * 2 / byclear,
    //   imgH: e.detail.height * 2 / byclear
    // })
    // const imgRef = this.selectComponent('#imgRef');
    // const query = wx.createSelectorQuery()
  },

  drawImg() {
    // 拦截频繁绘制
    if (this.data.drawing) return;
    this.data.drawing = true;
    var ctx = this.data.canvasContext;

    // 改变坐标系原点
    ctx.translate(this.data.change.x, this.data.change.y);
    ctx.scale(this.data.scale, this.data.scale);

    // 绘制图片
    // ctx.drawImage(
    //   this.img,
    //   0,
    //   0,
    //   this.data.viewWidth * this.data.scale,
    //   (this.data.viewWidth / this.rate) * this.data.scale
    // );
    // 使用scale
    ctx.drawImage(
      this.img,
      0,
      0,
      this.data.viewWidth,
      this.data.viewWidth / this.rate
    );
    // ctx.drawImage(this.img, 0, 0, this.data.width * this.data.scale, this.data.height * this.data.scale);
    console.log("drawImg---------------------");

    // 绘制图标文字
    // ctx.setFillStyle("#FF8000");
    ctx.setFontSize(12);
    ctx.setTextAlign("center");
    ctx.setTextBaseline("middle");

    // ctx.setFillStyle("#FF8000");
    // drawRectangle1(ctx, 50, 50, 50, 50, 10, 10,10,10);
    // ctx.arc(item[0] + item[3] / 2, item[1] + item[3] / 2, 10, 0, 2 * Math.PI);
    // ctx.setFillStyle("#FF8000");
    // ctx.fill();
    this.data.numArr.forEach((item) => {
      // ctx.fillRect(item[0], item[1], 20 * this.data.scale, 20 * this.data.scale);
      // ctx.arc(item[0] + item[3] / 2, item[1] + item[3] / 2, 10, 0, 2 * Math.PI);
      // ctx.setFillStyle("#FF8000");
      // ctx.fill();
      const colorMap = {
        fillColor: item[5] ? "rgba(255,128,0,0.9)" : "rgba(222,225,232,0.9)",
        fontColor: item[5] ? "#FFFFFF" : "#545861",
      };
      drawRectangle1(
        ctx,
        item[0],
        item[1],
        item[3],
        item[4],
        colorMap.fillColor,
        item[6],
        5,
        5,
        5,
        5
      ); // 画圆角矩形

      // ctx.setFillStyle("blue");
      // ctx.fillRect(item[0], item[1], item[3], item[4]); // 画方角矩形

      // drawRectangle(ctx, item[0], item[1], item[3], item[4], 3)

      ctx.setFillStyle(colorMap.fontColor);
      // ctx.setFillStyle("blue");
      ctx.fillText(item[2], item[0] + item[3] / 2, item[1] + item[4] / 2);

      // ctx.fill()
    });

    ctx.draw(
      false,
      (() => {
        console.log("drawImg11111111111111111111");
        this.data.drawing = false;
      })()
    );

    // ctx.setFillStyle('red')
    // ctx.fillRect(0,0,this.data.width * this.data.scale, this.data.height * this.data.scale)
    // ctx.draw(false, () => {
    //   console.log('drawImg11111111111111111111');
    //   this.data.drawing = false
    // });
  },
  /**
   * 限制 x、y 拖动范围，禁止滑出边界
   * @param {number} x
   * @param {number} y
   */
  checkRange(point) {
    point.x = Math.min(
      Math.max(
        point.x,
        -this.data.width * this.data.scale + this.data.viewWidth
      ),
      0
    );
    point.y = Math.min(
      Math.max(
        point.y,
        -this.data.height * this.data.scale + this.data.viewHeight
      ),
      0
    );
    return point;
  },
  /**
   * 缩放画布
   * @param {boolean} reduce 是否缩小，否则为放大
   */
  scaleCanvas(reduce, e) {
    let last = this.data.scale;
    let scale = Math.round(last * 100); // 转为整数计算，无精度丢失问题
    if (reduce) {
      // 缩小 / 鼠标滚轮向下滚动
      scale =
        scale > this.data.minScale
          ? scale - this.data.increaseScale
          : this.data.minScale;
    } else {
      // 放大 / 鼠标滚轮向上滚动
      scale =
        scale < this.data.maxScale
          ? scale + this.data.increaseScale
          : this.data.maxScale;
    }
    if (last !== scale / 100) {
      this.data.scale = scale / 100;
      this.data.start = {
        x: 0,
        y: 0,
      };
      // 参考问题：有一个长4000px、宽4000px的四方形ABCD，A点的坐标固定在(-2000,-2000)，
      // 			该四边形上有一个点E，坐标为(-100,-300)，将该四方形复制一份并缩小到90%后，
      // 			新四边形的A点坐标为多少时可使新四边形的E点与原四边形的E点重合？
      // 预期效果：从图中选取某点（参照物）为中心点进行缩放，缩放时无论图像怎么变化，该点位置始终固定不变
      // 计算方法：以相同起点先计算缩放前后两点间的距离，再加上原图像偏移量即可
      this.movingCanvas({
        isScaled: true,
        pageX: (e.pageX - this.data.change.x) * (1 - this.data.scale / last),
        pageY: (e.pageY - this.data.change.y) * (1 - this.data.scale / last),
      });
      // this.drawImg();
    }
  },

  onDbClick(e) {
    if (
      this.data.scale !== 1 ||
      this.data.change.x !== 0 ||
      this.data.change.y !== 0
    ) {
      this.data.scale = 1;
      (this.data.change = {
        x: 0,
        y: 0,
      }),
        (this.data.uDData = {
          x: 150,
          y: 150,
        });
      this.drawImg();
    } else {
      if (this.data.change.x === 0 && this.data.change.y === 0) {
        // this.data.scale = 1.45;
        this.data.uDData.x += 50;
        this.data.uDData.y = this.data.uDData.y + 50;

        this.data.increaseScale = 50;
        this.scaleCanvas(false, {
          pageX: this.data.uDData.x,
          pageY: this.data.uDData.y,
        });
        this.data.increaseScale = 5;
      }
    }
  },

  onTouchStart(e) {
    if (this.locating) return;
    this.data.start.x = e.touches[0].pageX;
    this.data.start.y = e.touches[0].pageY;
    this.data.touchType = "";

    console.log(e.touches[0].pageX, e.touches[0].pageY, "start");

    if (e.touches.length === 1) {
      const curTime = e.timeStamp;
      const lastTime = this.lastTapTimeStamp;
      const ctx = this.data.canvasContext;
      if (lastTime > 0 && curTime - lastTime < 300) {
        this.onDbClick(e);
      } else {
        this.data.numArr.forEach((item) => {
          if (
            this.data.change.x + item[0] * this.data.scale <=
              e.touches[0].pageX &&
            e.touches[0].pageX <=
              this.data.change.x + (item[0] + 22) * this.data.scale &&
            this.data.change.y + item[1] * this.data.scale <=
              e.touches[0].pageY &&
            e.touches[0].pageY <=
              this.data.change.y + (item[1] + 22) * this.data.scale
          ) {
            console.log("点击了", item[2]);
            item[5] = !item[5];
          }
        });

        this.drawImg();
      }
      this.lastTapTimeStamp = curTime;
    }
  },
  /**
   * 计算两点间距
   * @param {Object} touches
   */
  getDistanceByTouches(touches) {
    // 根据勾股定理求两点间距离
    const a = touches[1].pageX - touches[0].pageX;
    const b = touches[1].pageY - touches[0].pageY;
    const c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
    // 求两点间的中点坐标
    // 1. a、b可能为负值
    // 2. 在求a、b时，如用touches[1]减touches[0]，则求中点坐标也得用touches[1]减a/2、b/2
    // 3. 同理，在求a、b时，也可用touches[0]减touches[1]，则求中点坐标也得用touches[0]减a/2、b/2
    const x = touches[1].pageX - a / 2;
    const y = touches[1].pageY - b / 2;
    // return { a: Math.abs(a), b: Math.abs(b), c, x, y };
    return {
      c,
      x,
      y,
    };
  },

  touchmoveHandler(e) {
    if (this.locating) return;
    if (this.timer) {
      clearTimeout(this.timer);
    }
    this.timer = setTimeout(() => {
      this.onTouchMove(e);
    }, 12);
    // this.onTouchMove(e)
  },
  onTouchMove(e) {
    // if(this.locating) return;
    if (e.touches.length === 2) {
      // 双点触摸 / 缩放
      if (this.data.touchType === "scale") {
        const start = this.getDistanceByTouches(this.data.touches);
        const end = this.getDistanceByTouches(e.touches);
        if (Math.abs(start.c - end.c) >= 10) {
          // 滑动多长距离触发缩放
          this.data.touches = e.touches;
          this.scaleCanvas(
            start.c > end.c, // 两点间距变小=缩小
            {
              pageX: end.x,
              pageY: end.y,
            }
          );
        }
      } else {
        this.data.touches = e.touches;
      }
      this.data.touchType = "scale";
    } else {
      if (this.data.touchType === "scale") {
        // 从双点触摸变成单点触摸 / 从缩放变成拖动
        this.data.start.x = e.touches[0].pageX;
        this.data.start.y = e.touches[0].pageY;
        this.data.touchType = "move";
        return;
      }

      this.movingCanvas(e.touches[0]);
      this.data.touchType = "move";
    }
  },

  // 定义缓动函数，使用二次缓动函数
  easeOutQuad(t, b, c, d) {
    t /= d;
    return -c * t * (t - 2) + b;
  },

  // 定义函数，将点 (x1, y1) 缓动移动到第一象限的点 (x0, y0)
  // function moveToFirstQuadrantWithEasing(x1, y1, x0, y0, duration) {
  //     const start = { x: x1, y: y1 };
  //     const change = { x: x0 - x1, y: y0 - y1 };
  //     const startTime = performance.now();

  //     function animate() {
  //         const currentTime = performance.now();
  //         const elapsed = currentTime - startTime;
  //         const t = elapsed / duration;

  //         if (t < 1) {
  //             const newX = easeOutQuad(t, start.x, change.x, 1);
  //             const newY = easeOutQuad(t, start.y, change.y, 1);
  //             console.log(`移动中: (${newX.toFixed(2)}, ${newY.toFixed(2)})`);
  //             requestAnimationFrame(animate);
  //         } else {
  //             console.log(`到达目标点: (${x0}, ${y0})`);
  //         }
  //     }

  //     requestAnimationFrame(animate);
  // }

  // 示例：将点 (-3, -4) 缓动移动到第一象限的点 (5, 6)，动画持续时间为 2000 毫秒
  // const originalPoint = { x1: -3, y1: -4 };
  // const targetPoint = { x0: 5, y0: 6 };
  // const duration = 2000; // 动画持续时间，单位为毫秒

  // moveToFirstQuadrantWithEasing(originalPoint.x1, originalPoint.y1, targetPoint.x0, targetPoint.y0, duration);
  movingCanvas(touche) {
    console.log(touche.pageX, touche.pageY, "movingCanvas");

    let point = {
      x: this.data.change.x + touche.pageX - this.data.start.x,
      y: this.data.change.y + touche.pageY - this.data.start.y,
    };
    // this.data.checkRange(point);
    if (
      touche.isScaled ||
      this.data.change.x !== point.x ||
      this.data.change.y !== point.y
    ) {
      this.data.change = point;
      // this.data.numArr.forEach({})
      this.drawImg();
      this.data.start.x = touche.pageX;
      this.data.start.y = touche.pageY;
    }
  },
  // 放大缩小中心点坐标 pageX 227 pageY 91.75
  imgUp() {
    if (this.locating) return;
    this.data.uDData.x = this.data.uDData.x + 5;
    this.data.uDData.y = this.data.uDData.x + 5;
    // this.data.uDData.y = this.data.uDData.y + 5;
    this.scaleCanvas(false, {
      pageX: this.data.uDData.x,
      pageY: this.data.uDData.y,
    });
  },
  imgDn() {
    if (this.locating) return;
    this.data.uDData.x = this.data.uDData.x - 5;
    this.data.uDData.y = this.data.uDData.x - 5;
    // this.data.uDData.y = this.data.uDData.y - 5;
    this.scaleCanvas(true, {
      pageX: this.data.uDData.x,
      pageY: this.data.uDData.y,
    });
  },

  locatePoint(e, targetIndex = 17) {
    if (this.locating) return;
    this.locating = true;
    const targetItem = this.data.numArr.find((item) => {
      item[6] = false;
      item[3] = item[4] = 22;
      return item[2] === targetIndex;
    });
    const targetX = Number.parseFloat((this.data.change.x + (targetItem[0] + 11) * this.data.scale).toFixed(2)),
      targetY = Number.parseFloat((this.data.change.y + (targetItem[1] + 11) * this.data.scale).toFixed(2));

    targetItem[6] = true;
    targetItem[3] = targetItem[4] = 28;

    // 中点
    const centerX =
      (this.data.viewWidth * this.data.containerStyle.width) / 100 / 2;
    const centerY =
      (this.data.viewHeight * this.data.containerStyle.height) / 100;
    // const centerX = this.data.canvasContext._context.canvas.width / 2;
    // const centerY = this.data.canvasContext._context.canvas.height / 2;

    if ( Math.abs(targetX - centerX) < 1 && Math.abs(targetY - centerY) < 1) return this.locating = false;

    const increaseRate = Math.abs((centerX - targetX) / (centerY - targetY));

    // let operatorX = 1,
    //   operatorY = 1;
    // if (targetX > centerX) operatorX = -1;
    // if (targetY > centerY) operatorY = -1;

    this.data.start = {
      x: targetX,
      y: targetY,
    };

    const start = { x: targetX, y: targetY };
    const change = { x: centerX - targetX, y: centerY - targetY };
    const duration = 160, fps = 60;

    const steps = (duration * fps) / 1000; // 计算总步数
    let currentStep = 0;

    const intervalId = setInterval(() => {
      const t = currentStep / steps; // 当前时间比例

      if (t < 1) {
        const newX = this.easeOutQuad(t, start.x, change.x, 1);
        const newY = this.easeOutQuad(t, start.y, change.y, 1);
        // console.log(`移动中: (${newX.toFixed(2)}, ${newY.toFixed(2)})`);
        this.movingCanvas({
          pageX: Number.parseFloat((newX.toFixed(2))),
          pageY: Number.parseFloat((newY.toFixed(2))),
        });
        console.log('change', this.data.change.x,this.data.change.y);
        currentStep++;
      } else {
        console.log(`到达目标点: (${centerX}, ${centerY})`);
        clearInterval(intervalId); // 清除定时器
        this.locating = false;
      }
    }, 1000 / fps); // 每帧的时间间隔

    // const increaseNum = 1;

    // 没有动画
    // const moveX = centerX;
    // const moveY = centerY;
    // this.movingCanvas({
    //   pageX: moveX,
    //   pageY: moveY,
    // });

    // 动画
    // let moveX = targetX,
    //   moveY = targetY;

    // clearInterval(this.timer1);
    // this.timer1 = setInterval(() => {

    //   var stepY = Math.ceil((centerY - this.data.start.y) / 10) === -0;
    //   var stepX = Math.ceil(stepY * increaseRate);
    //   if (moveX * operatorX >= centerX || moveY * operatorY >= centerY) {
    //     clearInterval(this.timer1);
    //     this.locating = false;
    //   }
    //   (moveX += stepX * operatorX), (moveY += stepY * operatorY);
    //   this.movingCanvas({
    //     pageX: moveX,
    //     pageY: moveY,
    //   });
    // }, 16);

    // this.timer1 = setInterval(() => {
    //   moveX += increaseNum * increaseRate * operatorX, moveY += increaseNum * operatorY;
    //   this.movingCanvas({
    //     pageX: moveX,
    //     pageY: moveY,
    //   });
    //   if(moveX >= centerX || moveY >= centerY) clearInterval(this.timer1);
    // }, 16);
  },

  changeContainer() {
    this.setData({
      "containerStyle.height": this.data.containerStyle.height === 70 ? 30 : 70,
    });
  },

  getImage() {
    return new Promise((resolve) => {
      wx.getImageInfo({
        // src: "https://ts1.cn.mm.bing.net/th/id/R-C.21897809d2a33f83c7f8e0b53b4e08cf?rik=7nrC2zDBthZZmg&riu=http%3a%2f%2fstatic.zhizaoyun.com%2fglib%2f4_1_79014%2fimage530x430%2f20140605082757905.png&ehk=YkFjTzCHK1AnOJPPOTzFf%2fjQCi4kItbcW9%2fu7wnrkqs%3d&risl=&pid=ImgRaw&r=0&sres=1&sresct=1",
        src: `https://ts1.cn.mm.bing.net/th/id/R-C.d1d0e315192aaad61e173e62fd5f7596?rik=wbIeljJ9PL0qtw&riu=http%3a%2f%2fn.sinaimg.cn%2ftranslate%2fw474h1589%2f20180205%2fHd4Z-fyrhcqy5792749.jpg&ehk=eYb4ZTHuNZKyYraHJAtkPCARgWknaRoTQj%2bGfgy98NA%3d&risl=&pid=ImgRaw&r=0`,
        success: (res) => {
          console.log(res.path, "s2");
          let path = res.path;
          this.img = path;
          this.data.width = res.width;
          this.data.height = res.height;
          this.rate = this.data.width / this.data.height;
          resolve(path);
        },
      });
    });
  },
  onReady() {
    const that = this;
    const sys = wx.getSystemInfoSync();
    let y,
      a = 0;

    this.data.numArr = Array.from({ length: 50 }).map((_, index) => {
      let x = (index % 10) * 30;
      if (index % 10 === 0) {
        y = ++a * 30;
      }
      return [x, y, index, 22, 22, false, false];
    });

    this.timer = null;

    this.data.viewWidth = sys.screenWidth;
    this.data.viewHeight = sys.screenHeight / 2;
    this.data.canvasContext = wx.createCanvasContext("gameCanvas");

    // const query = wx.createSelectorQuery();
    // const imgRef = query.select('#imgRef');
    this.getImage().then(() => {
      that.drawImg();
    });
    // this.getImage()
    // that.drawImg()

    // wx.createSelectorQuery().select('#gameCanvas').fields({
    //   node: true,
    //   size: true
    // }).exec(res => {
    //      let ctx = res[0].node.getContext('2d');//getContext返回Canvas 的绘图上下文
    // });

    // test 纷享h5是否有 wx
    // 监听 PC 端鼠标滚轮
    if (wx.platform === "window") {
      window.addEventListener("mousewheel", (e) => {
        this.scaleCanvas(e.deltaY > 0, e);
      });
    }
  },
});
